﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Vit.Web.Data;

namespace Vit.Web.Services
{
    public class DataSourceService : IDataSourceService
    {
        private readonly IUnityContainer container;

        public DataSourceService(IUnityContainer container)
        {
            this.container = container;
        }

        #region IDataSourceService Members

        public object GetSourceData(Type entityType, params object[] paras)
        {
            try
            {
                var provider = container.Resolve<IDataSourceProvider>(entityType.AssemblyQualifiedName);
                return provider.GetData(paras);
            }
            catch
            {
                return null;
            }
        }

        public object GetSourceData<T>(Type entityType, string dataSourceName, params object[] paras)
        {
            try
            {
                var provider = container.Resolve<IDataSourceProvider>(entityType.AssemblyQualifiedName);
                return provider.GetData(dataSourceName, paras);
            }
            catch
            {
                return null;
            }
        }

        public IEnumerable<SelectListItem> GetSourceListItems(Type entityType, params object[] paras)
        {
            try
            {
                var provider = container.Resolve<IDataSourceProvider>(entityType.AssemblyQualifiedName);
                return provider.GetListItems(paras);
            }
            catch
            {
                return null;
            }
        }

        public IEnumerable<SelectListItem> GetSourceListItems(Type entityType, string dataSourceName, params object[] paras)
        {
            try
            {
                var provider = container.Resolve<IDataSourceProvider>(entityType.AssemblyQualifiedName);
                return provider.GetListItems(dataSourceName, paras);
            }
            catch
            {
                return null;
            }
        }

        public string GetDisplayText(Type entityType, params object[] ids)
        {
            try
            {
                var provider = container.Resolve<IDataSourceProvider>(entityType.AssemblyQualifiedName);
                return provider.GetDisplayText(ids);
            }
            catch
            {
                return string.Empty;
            }
        }

        #endregion
    }
}
